package com.lucene.controller;
import com.lucene.service.WechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhangzhen on 29/09/2017.
 */
@Component
@RestController
@RequestMapping(value = "/wechat")
public class WeChatController{

    private static Logger logger = LoggerFactory.getLogger(WeChatController.class);
    @RequestMapping(value = "/init")
    public ModelAndView loginWeChatPage(){
        return new ModelAndView("login");
    }

    @RequestMapping(value = "/load")
    public void loginWeiChatPage(HttpServletResponse resp) throws IOException {
        logger.info("[*] 初始化获取微信二维码.");
        WechatService ws = WechatService.build(null);
        try {
            logger.info("[*] 正在获取 uuid ... ");
            ws.getUUID();
            logger.info("[*] 正在获取二维码 ... 成功\n");
            logger.info("[*] 请使用微信扫描二维码以登录 ... \n");
            byte[] qrcode = ws.getQrcodeBytes();
            //2. 输出微信登录页面
            InputStream in = new ByteArrayInputStream(qrcode);
            BufferedImage image = ImageIO.read(in);
            resp.setHeader("Pragma", "no-cache");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setDateHeader("Expires", 0);
            resp.setContentType("image/jpeg");
            ServletOutputStream sos = resp.getOutputStream();
            ImageIO.write(image, "jpeg", sos);
            sos.flush();
            sos.close();
            ws.setStatus("wait4login");//waiting for scan sq
        }catch (IOException e){
            ws.setStatus(null);//waiting for scan sq
            e.printStackTrace();
            logger.error("[*] SQ_CODE 输出异常...");
        }
    }
}
